#define _CRT_SECURE_NO_WARNINGS

#include "common.h"

#include <direct.h>
#include <list>
#include <fstream> 

using namespace std;

string GetPathDir(string filePath)
{
	string dirPath = filePath;
	size_t p = filePath.find_last_of('/');
	if (p != -1)
	{
		dirPath.erase(p);
	}
	return dirPath;
}

void CreateMultiLevel(string dir)
{
	if (!_chdir(dir.c_str()))
	{
		return;
	}

	list <string> dirList;
	dirList.push_front(dir);

	string curDir = GetPathDir(dir);
	while (curDir != dir)
	{
		if (!_chdir(curDir.c_str()))
		{
			break;
		}

		dirList.push_front(curDir);

		dir = curDir;
		curDir = GetPathDir(dir);
	}

	for (auto it : dirList)
	{
		_mkdir(it.c_str());
	}
}


bool common::mkdirs(const char* path) {
	CreateMultiLevel(path);
	return true;
};

bool common::write_file(const char* filename, const char* buf, unsigned long buf_len) {
	ofstream ofs;
	ofs.open(filename, ios::binary);
	for (int i = 0; i < buf_len; i++) {
		ofs << buf[i];
	}
	ofs.close();
	return true;
};
